package com.ilop.sthome.utils.greenDao.utils;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.greenDao.DefaultBean;
import com.ilop.sthome.data.greenDao.DefaultBeanDao;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.ParsingJsonUtil;
import com.ilop.sthome.utils.greenDao.manage.CommonDaoUtils;
import com.ilop.sthome.utils.greenDao.manage.DaoManager;

import java.util.ArrayList;
import java.util.List;

public class DefaultDaoUtil {

    private volatile static DefaultDaoUtil instance = null;
    private CommonDaoUtils<DefaultBean> mDefaultUtils;
    private DefaultBeanDao mDefaultDao;

    public static DefaultDaoUtil getInstance(){
        if (instance == null){
            synchronized (DefaultDaoUtil.class){
                if (instance == null){
                    instance = new DefaultDaoUtil();
                }
            }
        }
        return instance;
    }

    public static void setInstance(){
        instance = null;
    }

    private DefaultDaoUtil() {
        DaoManager mManager = DaoManager.getInstance();
        mDefaultDao = mManager.getDaoSession().getDefaultBeanDao();
        mDefaultUtils = new CommonDaoUtils(DefaultBean.class, mDefaultDao);
    }

    public CommonDaoUtils<DefaultBean> getDefaultDao(){
        return mDefaultUtils;
    }

    /**
     * 根据设备常用功能Id
     * @param context 上下文
     * @param recommendIds 推荐场景Id
     * @param device 当前设备
     */
    public void setDefaultList(Context context, String[] recommendIds, DeviceInfoBean device){
        String common = ParsingJsonUtil.getInstance().getJson(context, "device_functions.json");
        List<DefaultBean> defaultList = JSON.parseArray(common, DefaultBean.class);
        for (String id:recommendIds) {
            for (DefaultBean bean:defaultList) {
                if (bean.getRecommendId().equals(id)){
                    bean.setDeviceId(CoderUtils.setCodeSupplement2Byte(Integer.toHexString(device.getDevice_ID())));
                    bean.setDeviceName(device.getDeviceName());
                    bean.setDeviceType(device.getDevice_type());
                    mDefaultUtils.insert(bean);
                    break;
                }
            }
        }
    }

    /**
     * 根据设备类型查询默认自动化
     * @param device 子设备
     * @return 所有该设备的默认自动化
     */
    public List<DefaultBean> findDefaultByDevice(DeviceInfoBean device){
        String deviceId = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(device.getDevice_ID()));
        return mDefaultUtils.queryByQueryBuilder(
                DefaultBeanDao.Properties.DeviceName.eq(device.getDeviceName()),
                DefaultBeanDao.Properties.DeviceType.eq(device.getDevice_type()),
                DefaultBeanDao.Properties.DeviceId.eq(deviceId));
    }

    /**
     * 功能是否存在所需设备类型
     * @param defaultBean 推荐自动化
     * @return 存在
     */
    public int findDefaultHasType(DefaultBean defaultBean){
        int hasDevice = -1;
        String outputCode = defaultBean.getOutputCode();
        String deviceType = outputCode.substring(0, 4);
        if (!"FFFF".equals(deviceType)){
            String deviceName = defaultBean.getDeviceName();
            String actionCode = outputCode.substring(8);
            String[] typeList = SmartDevice.getType(deviceType).getDevType();
            for (String type:typeList) {
                List<DeviceInfoBean> device = DeviceDaoUtil.getInstance().findDeviceByType(deviceName, type);
                if (device.size() == 0){
                    hasDevice =  -1;
                }else {
                    String device_id = Integer.toHexString(device.get(0).getDevice_ID());
                    String output = type + CoderUtils.setCodeSupplement2Byte(device_id) + actionCode;
                    defaultBean.setOutputCode(output);
                    DefaultDaoUtil.getInstance().getDefaultDao().update(defaultBean);
                    hasDevice = device.get(0).getDevice_ID();
                    break;
                }
            }
            return hasDevice;
        }else {
            return 0;
        }
    }

    /**
     * 获取常用功能输出条件
     * @param defaultBean 常用功能
     * @return
     */
    public List<DeviceInfoBean> getDefaultOutputList(DefaultBean defaultBean) {
        List<DeviceInfoBean> mOutputList = new ArrayList<>();
        String outputCode = defaultBean.getOutputCode();
        int output = getGatewayDevice(outputCode);
        int positionOut = 0;
        for (int i = 0; i < output; i++) {
            DeviceInfoBean device = new DeviceInfoBean();
            String deviceType = outputCode.substring(positionOut, positionOut + 4);
            int deviceId = Integer.parseInt(outputCode.substring(positionOut + 4, positionOut + 8), 16);
            String action = outputCode.substring(positionOut + 8, positionOut + 10);
            if ("FFFF".equals(deviceType) && deviceId == 0) {
                if ("82".equals(action)) {
                    device.setDevice_type("PHONE");
                    device.setDevice_ID(deviceId);
                } else {
                    device.setDevice_type("GATEWAY");
                    device.setDevice_ID(deviceId);
                }
            } else {
                device.setDevice_type(deviceType);
                int hasDevice = findDefaultHasType(defaultBean);
                if (hasDevice == -1) {
                    device.setDevice_ID(deviceId);
                    device.setCurrent_mode(198);
                }else {
                    device.setDevice_ID(hasDevice);
                }
            }
            int actionLength = positionOut + 10 + Integer.parseInt(action.substring(1)) * 2;
            String fullAction = outputCode.substring(positionOut + 8, actionLength);
            device.setDevice_status(fullAction);
            device.setDeviceName(defaultBean.getDeviceName());
            mOutputList.add(device);
            positionOut = actionLength;
        }
        return mOutputList;
    }

    private int getGatewayDevice(String code) {
        int mLength = code.length();
        if (mLength>14) {
            String after_str = code.replaceAll("FFFF0000", "");
            //获取替换后的字符串的长度
            int after_len = after_str.length();
            //要被查找的元素的个数=原长度-替换后的长度
            int end = code.length() - after_len;
            return end/8;
        }else {
            return 1;
        }
    }

    /**
     * 删除网关下的所有默认功能
     * @param deviceName 网关
     */
    public void deleteByDeviceName(String deviceName){
        mDefaultUtils.deleteByQuery(DefaultBeanDao.Properties.DeviceName.eq(deviceName));
    }

    /**
     * 删除该子设备的所有常用功能
     * @param deviceName 网关
     * @param deviceId 设备ID
     */
    public void deleteByDeviceId(String deviceName, int deviceId){
        String mDeviceId = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(deviceId));
        mDefaultUtils.deleteByQuery(DefaultBeanDao.Properties.DeviceName.eq(deviceName),
                DefaultBeanDao.Properties.DeviceId.eq(mDeviceId));
    }
}
